import { format as dateFormat } from 'date-fns';
import ms from 'ms';
export const number = (() => {
  const format = new Intl.NumberFormat('en-US').format;
  return (n) => {
    if (!n) return '0';
    return format(n);
  };
})();

export function percent (t) {
  if (isNaN(t)) return '0%';
  const percentFormat = new Intl.NumberFormat('en-US', {
    style: 'percent',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format;
  return percentFormat(t);
}

export function datetime (t, p) {
  try {
    const d = new Date(t || '');
    if (!t || d.getTime() === 0) return '';
    const formatStr = typeof p === 'string' ? p : 'yyyy-MM-dd HH:mm:ss';
    return dateFormat(d, formatStr);
  } catch (error) {
    return '';
  }
}

export const numberCompact = new Intl.NumberFormat('zh-CN', {
  notation: 'compact',
}).format;

export const millisecond = (() => {
  let format;
  try {
    format = new Intl.NumberFormat('en', {
      style: 'unit',
      unit: 'millisecond',
    }).format;
  } catch (error) {
    // 兼容 chrome 71, 不支持 style: 'unit'
    format = (num) => {
      const formattedNum = new Intl.NumberFormat('en', {
        unit: 'millisecond',
      }).format(num);
      return `${formattedNum} ms`;
    };
  }

  return (x) => (Number.isFinite(x - '') ? format(x) : null);
})();

const durationParts = [
  {
    textUnit: '天',
    shortUnit: 'd ',
    ms: 24 * 60 * 60 * 1000,
    isShortUnit: false,
    isTextUnit: true,
  },
  {
    textUnit: '小时',
    shortUnit: ':',
    ms: 60 * 60 * 1000,
    isShortUnit: true,
    isTextUnit: true,
  },
  {
    textUnit: '分钟',
    shortUnit: ':',
    ms: 60 * 1000,
    isShortUnit: true,
    isTextUnit: true,
  },
  {
    textUnit: '秒',
    shortUnit: '',
    ms: 1000,
    isShortUnit: true,
    isTextUnit: false,
  },
];
export function duration (milliseconds, useTextUnit = true) {
  const parts = durationParts.filter((x) => (!useTextUnit ? x.isShortUnit : x.isTextUnit));

  let { ret, current } = parts.reduce(
    (obj, { textUnit, shortUnit, ms }, idx) => {
      const u = useTextUnit ? textUnit : shortUnit;
      if (obj.current >= ms) {
        const isLast = idx === parts.length - 1;
        let n = obj.current / ms;
        n = isLast ? Math.ceil(n) : parseInt(n, 10);
        obj.ret += `${useTextUnit ? n : String(n || 0).padStart(2, '0')}${u}`;
        obj.current = obj.current % ms;
      } else if (useTextUnit ? obj.ret : true) {
        obj.ret += `${useTextUnit ? '0' : '00'}${u}`;
      }
      return obj;
    },
    {
      current: milliseconds,
      ret: '',
    }
  );

  if (!ret && useTextUnit) {
    if (current > 0) {
      current = Math.ceil(current / 1000);
      ret = `${current}秒`;
    } else {
      ret = '0秒';
    }
  }

  return ret;
}
export const FREQ_UNIT_MAP = {
  m: '分钟',
  h: '小时',
  d: '天',
  w: '周',
  month: '月',
};
export function timeChange (value) {
  let unit;
  let num;
  if (value) {
    const freq = ms(value);
    unit = value ? freq.replace(/\d*/, '') : 'd';
    num = parseInt(freq.replace(/[a-zA-Z]/, ''), 10);
    if (value % ms('30d') === 0) {
      unit = 'month';
      num = value / ms('30d');
    } else if (value % ms('1w') === 0) {
      unit = 'w';
      num = value / ms('1w');
    }
  }
  // 3小时/5分钟/2天
  return `${num}${FREQ_UNIT_MAP[unit] || '毫秒'}`;
}
